package com.stylefeng.guns.modular.huamao.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.IUsersRealnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.service.IUsersService;
import com.stylefeng.guns.modular.huamao.util.AddressUtils;
import com.stylefeng.guns.modular.huamao.util.GunsProperties;
import com.stylefeng.guns.modular.huamao.util.IpAddressUtils;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;


/**
 * 用户管理控制器
 *
 * @author fengshuonan
 * @Date 2018-04-10 19:42:53
 */
@CrossOrigin()
@Controller
@RequestMapping("/users")
public class UsersController extends BaseController {

	private String PREFIX = "/huamao/users/";
	
	@Autowired
	private IUsersService usersService;
	@Autowired
    private GunsProperties gunsProperties;
	@Autowired
	private IUsersRealnameService  usersRealnameService;
	/**
	 * 跳转到用户管理首页
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "users.html";
	}

	/**
	 * 跳转到添加用户管理
	 */
	@RequestMapping("/users_add")
	public String usersAdd() {
		return PREFIX + "users_add.html";
	}

	/**
	 * 跳转到修改用户管理
	 */
	@RequestMapping("/users_update/{usersId}")
	public String usersUpdate(@PathVariable Integer usersId, Model model) {
		UsersDTO usersDTO = new UsersDTO();
		usersDTO.setUserId(usersId);
		usersDTO = usersService.selectOneUsersInfo(usersDTO);
		model.addAttribute("item", usersDTO);
		return PREFIX + "users_edit.html";
	}

	/**
	 * 获取用户管理列表
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(UsersDTO usersDTO) {
		return usersService.selectUsersInfo(usersDTO);
	}
	/**
	 * 推荐列表
	 */
	@RequestMapping(value = "/tuiList/{inviteId}")
	@ResponseBody
	public Object tuiList(@PathVariable Integer inviteId) {
		List<UsersDTO> list = usersService.selectTuiUsersInfo(inviteId);
		return list;
	}
	/**
	 * 获取推荐人id，name，phone
	 * @param tuiPhone
	 * @return
	 */
	@RequestMapping(value = "selectTuiUsersName/{tuiPhone}")
	@ResponseBody
	public Object selectTuiUsersInfo(@PathVariable String tuiPhone) {
		Users users = new Users();
		users.setUserPhone(tuiPhone);
		users = usersService.selectTuiUsersName(users);
		return users;
	}
	/**
	 * 新增用户管理
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object add(Users users) {
		usersService.insert(users);
		return SUCCESS_TIP;
	}

	/**
	 * 删除用户管理
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(UsersDTO usersDTO) {
		usersService.deleteById(usersDTO.getInviteId());
		return SUCCESS_TIP;
	}


	
	/**
	 * 用户管理详情
	 */
	@RequestMapping(value = "/detail/{usersId}")
	@ResponseBody
	public Object detail(@PathVariable("usersId") Integer usersId) {
		return usersService.selectById(usersId);
	}
	
	/**
     * 根据用户id 姓名 电话查询身份
     */
	@RequestMapping(value = "/selectUsers")
	@ResponseBody
    public Object selectUsers(Users users){
		Map<String,Object> user = usersService.selectUsersPhone(users);
		return user;
    }
	
	/*******************登录**************************/
	/**
	 * 修改用户信息
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Result update(UsersDTO usersDTO) {
		String result = usersService.updateUsersInfo(usersDTO);
		if("1".equals(result)){
			return Result.OK("修改成功");
		}else{
			return Result.EEROR("修改失败");
		}
		
	}
	/**
	 * 用户登录信息后
	 * @param users
	 * @return
	 */
	@RequestMapping(value = "/userLogin")
	@ResponseBody
    public Result userLogin(Users users,HttpServletRequest request){
		String ip = IpAddressUtils.getIpAddr(request);
		UsersLoginDTO user = usersService.userLogin(users,ip);
		AddressUtils addressUtils = new AddressUtils();
		try {
			String loginRegion = addressUtils.getAddresses("ip=" + ip, "utf-8");
			user.setLoginRegion(loginRegion);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(ToolUtil.isEmpty(user)){
			return Result.EEROR("登录失败！");
		}
		if (user!=null){
			if ("0".equals(user.getUserStatus())){
				return Result.EEROR("该账户已锁定！");
			}
		}
		return Result.OK(user);
    }
	/**
	 * 核实用户信息
	 * @return
	 */
	@RequestMapping(value = "/checkUserInfo")
	@ResponseBody
    public Result userLogin(@RequestParam(value="phoneOrLoginName") String userPhoneOrloginName){
		Users user = usersService.checkUserPhoneOrloginName(userPhoneOrloginName);
		return Result.OK(user);
    }
	/**
     * 查询用户上10级
     */
    @RequestMapping("/userUpLevel")
    @ResponseBody
    public Result userUpLevel(@RequestParam(value="usersId") Integer id){
        Map<String,Object> map = usersService.selectUsersUpLevel(id);
        return Result.OK(map);
    }
    /**
     * 用户身份
     */
    @RequestMapping("/userIdentity")
    @ResponseBody
    public Result userIdentity(@RequestParam(value="userId") Integer id){
        UserIdentity userIdentity = usersService.userIdentity(id);
        if(ToolUtil.isEmpty(userIdentity)){
        	return Result.EEROR("用户身份查询失败！");
        }
        return Result.OK(userIdentity);
    }

    @RequestMapping("/selectByUsersInfoTwo")
    @ResponseBody
    public Result selectByUsersInfoTwo(@RequestParam(value="userId") Integer id){
        Map<String,Object> map  = new HashMap<String, Object>();

        UsersRealname  usersRealname = new UsersRealname();
        usersRealname.setUserId(id);
        EntityWrapper<UsersRealname>  entityWrapper = new EntityWrapper<UsersRealname>(usersRealname);
        Map<String,Object> usersRealnameMap = new HashMap<String,Object>();
        usersRealname = usersRealnameService.selectOne(entityWrapper);
        map.put("usersRealfalg",false);
        if(usersRealname != null){
            String name  =  usersRealname.getTrueName().substring(0,1)+"**";
            String cardID = usersRealname.getCardID().substring(0,4)+"****"+usersRealname.getCardID().substring(usersRealname.getCardID().length()-4);
            //usersRealnameMap.put("trueName",usersRealname.getTrueName());
            usersRealnameMap.put("trueName",name);
            //usersRealnameMap.put("cardID",usersRealname.getCardID());
            usersRealnameMap.put("cardID",cardID);
            map.put("usersRealfalg",true);
        }

        List<Map<String,Object>> mapList =  new ArrayList<Map<String, Object>>();
        Users users1 =  usersService.selectById(id);
		map.put("sharefalg",false);
        if(users1.getInviteId() != 0){
        	Users  users = new Users();
        	users.setUserId(users1.getInviteId());
        	EntityWrapper<Users> entityWrapper1 = new EntityWrapper<Users>(users);
			Users users2 = usersService.selectOne(entityWrapper1);
			Map<String,Object>  objectMap  = new HashMap<String, Object>();
			String name = users2.getTrueName().substring(0,1)+"**";
			String userPhone = users2.getUserPhone().substring(0,3)+"****"+users2.getUserPhone().substring(users2.getUserPhone().length()-3);
			objectMap.put("userId",users2.getUserId());
			objectMap.put("trueName",name);
			objectMap.put("userPhone",userPhone);
			mapList.add(objectMap);
			map.put("sharefalg",true);
		}

        map.put("usersReal",usersRealnameMap);
        map.put("share",mapList);
        return Result.OK(map);
    }
    /**
     * 根据Id查询注册信息
     */
    @RequestMapping("/selectByUsersInfo")
    @ResponseBody
    public Result getUserById(@RequestParam(value="userId") Integer id){
        Map<String,Object> usersMap= usersService.selectByUsersInfo(id);

        return Result.OK(usersMap);
    }
    /**
     * 修改用户密码
     */
    @RequestMapping("/updateUsersPwd")
    @ResponseBody
    public Result updateUsersPwd(UsersDTO users){
         int i = usersService.updateUsersPwd(users);
         return Result.OK(i);
    }
    /**
     * 找回密码   newLoginPwd 新密码 userPhone用户手机号
     */
    @RequestMapping("/findUsersPwd")
    @ResponseBody
    public Result findUsersPwd(UsersDTO users){
         int i = usersService.findUsersPwd(users);
         return i==0?Result.EEROR("找回密码失败"):Result.OK("找回密码成功");
    }
    /**
     * 修改用户支付密码
     */
    @RequestMapping("/updateUsersPayPwd")
    @ResponseBody
    public Result updateUsersPayPwd(UsersDTO users){
         int i = usersService.updateUsersPayPwd(users);
         return Result.OK(i);
    }
    /**
	 * 用户注册
	 */
	@RequestMapping(value = "/addUser")
	@ResponseBody
	public Result addUser(Users users) {
		String result = usersService.insertUsers(users);
		if("REPEAT".equals(result)){
			return Result.OK(result);
		}
		return Result.OK(null);
	}
	/**
	 * 查看该用户发展几个人
	 */
	@RequestMapping(value = "/developmentUser")
	@ResponseBody
	public Result developmentUser(Users users) {
		Integer  count= usersService.developmentUser(users);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("count", count);
		return Result.OK(map);
		
	}
	/**
	 * 修改线下商家 线上商家
	 */
	@RequestMapping(value = "/updateIsStoreOrIsShop")
	@ResponseBody
	public Result updateIsStoreOrIsShop(Users users) {
		boolean updateById = usersService.updateById(users);
		return updateById == true?Result.OK(null):Result.EEROR("修改联盟商家失败！");
	}
	/**
	 * 根据id查询 是否是线下商城
	 * @param users
	 * @return
	 */
	@RequestMapping(value = "/selectIsStore")
	@ResponseBody
	public Result selectIsStore(Users users) {
		if(ToolUtil.isEmpty(users.getUserId())){
			Users user = usersService.selectById(users.getUserId());
			return Result.OK(user.getIsStore());
		}
		return Result.EEROR("没有用户id");
	}
	/**
	 * 查看用户升级状态
	 * */
	@RequestMapping(value = "/upStauts")
	@ResponseBody
	public Result upStauts(Users users) {
		Integer updateById = usersService.upStauts(users);
		if(ToolUtil.isEmpty(updateById)){
			return Result.EEROR("没有升级状态！");
		}
		return  Result.OK(updateById);
	}
	/**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile picture) {
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        try {
            String fileSavePath = gunsProperties.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
            pictureName = "/kaptcha/"+pictureName;//保存数据库字段
        } catch (Exception e) {
            throw new GunsException(BizExceptionEnum.SIGN_ERROR);
        }
        return Result.OK(pictureName);
    }
    
}
